
var page_number = 1;
var action_name = "";
$(function(){

    action_name = get_current_action_name();
    page_number = 1;
    //订单结算界面
    if (action_name == "new") {

        var init_state = $("#init_state").val();

        if(init_state=="200"){

            GpsToBaiduMap = function (data) {
                if (data.status == 0) {
                    $("#address_info #latitude").val(data.points[0].lat);
                    $("#address_info #longitude").val(data.points[0].lng);
                }
            }
            //提示框
            jyd_loading_toast({'content': '正在定位'});
            wx.ready(function () {
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: function (res) {

                        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                        var speed = res.speed; // 速度，以米/每秒计
                        var accuracy = res.accuracy; // 位置精度
                        console.log("地址信息为：" + JSON.stringify(res));
                        var convertor = new BMap.Convertor();
                        var pointArr = [];
                        pointArr.push(new BMap.Point(res.longitude, res.latitude));
                        convertor.translate(pointArr, 1, 5, GpsToBaiduMap)
                        var req_url = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + res.latitude + "," + res.longitude + "&coord_type=1&key=ISRBZ-PPCWU-M4VVN-BL4LY-FH6NH-AWFA4&output=jsonp&callback=location_callback&jsoncallback=?";
                        $.getJSON(req_url, function (data) {
                            console.log("1反地址解析信息为：" + JSON.stringify(data));
                        });
                    }
                });
            });
            wx.error(function (res) {
                jyd_loading_toast_hide();
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
        }
    }else if(action_name=='index'){

        load_order_list();

    }
})


function order_list_event_lister_init(){

    //移除之前的监听
    $(".order_op").unbind("click");
    $(".order_item_container").unbind("click");

    $(".order_op").click(function(){
        event.stopPropagation();
    })

    $(".order_item_container").click(function(){
        var order_id = $(this).attr("id");
        location.href = "/order/show?order_id="+order_id;
    })
}

function load_order_list(){

    console.log("加载订单列表！");

    jyd_loading_toast({'content':'加载中……'});
    var customer_id = (get_current_customer_id()=="") ? get_current_business_id() : get_current_customer_id();
    //设置购物车数据
    var req_url = "/elephant_services/get_data?service_path=v1,order,search_orders_all&customer_id=" + customer_id+"&page="+page_number;
    //各门店有效订单量
    $.get(req_url, function (data, status) {
        //console.log(JSON.stringify(data));

        //移除之前的元素
        //$("#order_item_model").nextAll().remove();

        if(data.length == 0){
            $("#load_more_data").addClass("weui_btn_disabled").text("暂无数据！").attr("href","javascript:void(0);");
        }else{
            data.forEach(function(order){

                var order_state = get_order_state_text(order.workflow_state);//订单状态
                var order_time = order.created_at;//订单创建时间
                var paycost = order.paycost;//实付金额
                var paymode = get_paymode_text(order.paymode);//支付方式
                var model = $("#order_item_model").clone();

                model.find(".order_item_header .order_status .title").html(order_state);
                model.find(".order_item_header .order_time").html(order_time);

                model.find(".order_item_footer .order_paycost .paycost").html("¥ "+paycost);
                model.find(".order_item_header .order_paycost .paymode").html("（"+paymode+"）");

                model.find(".order_item_footer .order_op .order_confirm").attr({"href":"javascript:order_confirm('"+order.id+"');"});
                model.find(".order_item_footer .order_op .order_cancel").attr({"href":"javascript:jyd_dialog_confirm({content:\"确认取消当前订单吗？\",confirm_callback: function(){order_cancel('"+order.id+"');}});"});

                //["cancelled","completed","paid","generation"].includes(order.workflow_state)
                if("cancelled"==order.workflow_state || "completed"==order.workflow_state  || "paid"==order.workflow_state || "generation"==order.workflow_state){
                    model.find(".order_item_footer .order_op .order_confirm").hide();
                }

                if("cancelled"==order.workflow_state || "completed"==order.workflow_state  || "receive"==order.workflow_state){
                    model.find(".order_item_footer .order_op .order_cancel").hide();
                }

                //if(["cancelled","completed","paid","generation"].includes(order.workflow_state)){
                //    model.find(".order_item_footer .order_op .order_confirm").hide();
                //}
                //
                //if(["cancelled","completed","receive"].includes(order.workflow_state)){
                //    model.find(".order_item_footer .order_op .order_cancel").hide();
                //}

                //商品列表
                var product_html = "";
                order.ordergoods.forEach(function(ordergood){
                    product_html += "<a><img src=\""+ordergood.avatar_url+"\" alt=\"商品缩略图\"></a>";
                });
                model.find(".order_item_content").html(product_html);

                model.attr("id",order.id);
                model.show();
                $("#order_container").append(model);
            });
            order_list_event_lister_init();
        }
        jyd_loading_toast_hide();
        page_number += 1;
    });
}

function get_paymode_text(paymode){

    var text = "";
    switch (paymode){
        case 0:
            text = "待付款"
            break;
        case 1:
            text = "支付宝"
            break;
        case 2:
            text = "微信支付"
            break;
    }
    return text;
}

function get_order_state_text(workflow_state){

    var order_status = "";
    switch (workflow_state){
        case "generation":
            order_status = "待付款"
            break;
        case "paid":
            order_status = "待接单"
            break;
        case "take":
            order_status = "待接货"
            break;
        case "distribution":
            order_status = "配送中"
            break;
        case "receive":
            order_status = "配送完成"
            break;
        case "refunding":
            order_status = "退款中"
            break;
        case "cancelled":
            order_status = "已取消"
            break;
        case "completed":
            order_status = "已完成"
            break;
    }
    return order_status;
}


function location_callback(data){
    jyd_loading_toast_hide();
    if (data.status == 0) {
        console.log("反地址解析正常！");
        console.log("省：" + data.result.address_component.province + ",市：" + data.result.address_component.city + ",区：" + data.result.address_component.district);
        console.log("地址描述" + data.result.address);
        $("#address_info #address").val(data.result.address);
        $("#address_info #address_show").text(data.result.address);

    } else {
        console.log("反地址解析异常！");
        console.log("反地址解析信息为：" + JSON.stringify(data));
    }
}


//提交订单
function submit_order() {


    var latitude = $("#address_info #latitude").val();//纬度
    var longitude = $("#address_info #longitude").val();//经度
    var telephone = $("#address_info #telephone").val();//手机号
    var consignee = $("#address_info #consignee").val();//收货人
    var address = $("#address_info #address").val();//地址
    var remarks = $("#address_info #remarks").val();//备注
    var paymode = $("#paymode_info #paymode").val();//支付方式

    if (!(/^1[34578]\d{9}$/.test(telephone))) {
        jyd_toast({content: '请填写正确手机号！'});
        return;
    }

    //if(consignee==""){
    //    jyd_toast({content: '请填写收货人！'});
    //    return;
    //}

    var customer_id = (get_current_customer_id() == "") ? get_current_business_id() : get_current_customer_id();
    var req_params = {};
    req_params.userinfo_id = get_current_userinfo_id();
    req_params.customer_id = customer_id;
    req_params.consignee = consignee;
    req_params.address = address;
    req_params.lat = latitude;
    req_params.lng = longitude;
    req_params.telephone = telephone;
    req_params.temp_consignee = '';
    req_params.temp_telephone = '';
    req_params.os = 'wechat';
    req_params.version = '微信';
    req_params.useintegral = 0;
    req_params.jyd_coupon_customer_id = '';
    req_params.remarks = remarks;
    req_params.paymode = paymode;
    req_params.product_source = $("#product_source").val();
    req_params.activities = [];

    var activitie = {'preferential_way': 0, 'ordergoods': []}

    $("#product_list .weui_cell").each(function () {
        var quantity = $(this).find("[name='quantity']").val();
        var product_id = $(this).find("[name='product_id']").val();
        activitie.ordergoods.push({'product_id': product_id, 'quantity': quantity});
    })
    req_params.activities.push(activitie);


    jyd_loading_toast({'content': '处理中……'});
    var req_url = "/elephant_services/post_data?service_path=v2,order,make_sure_to_buy";
    $.post(req_url, {order: JSON.stringify(req_params)}, function (data, status) {
        jyd_loading_toast_hide();
        if (data.state == 200) {

            location.href = "/order/success?order_id="+data['order']['id'];
            //jyd_dialog_confirm({
            //    title: '提示信息',
            //    content: '订单提交成功！',
            //    cancel_content: '返回首页',
            //    confirm_content: '查看订单',
            //    cancel_callback: function(){
            //        location.href = "/";
            //    },
            //    confirm_callback:  function(){
            //        location.href = "/";
            //    }
            //})
            //jyd_toast({content: '恭喜您，订单提交成功！'})
        } else {
            jyd_toast({content: data.msg})
        }
    });
}


//更新购物车
function update_shoppingcart(product_data) {

    jyd_loading_toast({'content': '处理中'});

    product_data.split(',').forEach(function (product) {
        var product_infos = product.split(':');
        var product_id = product_infos[0];
        var state = product_infos[1];
        var stock = /^\d+$/.test(product_infos[2]) ? product_infos[2] : 0;

        //更新购物车气泡数量
        var customer_id = (get_current_customer_id() == "") ? get_current_business_id() : get_current_customer_id();
        var req_url = "/elephant_services/get_data?service_path=v2,shopping_cart,update&op=update&userinfo_id=" + get_current_userinfo_id() + "&customer_id=" + customer_id + "&product_id=" + product_id + "&number=" + stock;
        //各门店有效订单量
        $.get(req_url, function (data, status) {
            if (data.flag == 1) {
                console.log("更新购物车成功！");
            } else {
                console.log("更新购物车失败！");
            }
        });
    });
    jyd_loading_toast_hide();
    location.href = '/';
}

//确认收货
function order_confirm(order_id){

    jyd_loading_toast({'content':'加载中……'});
    //设置购物车数据
    var req_url = "/elephant_services/post_data?service_path=v1,order,confirm_receipt";
    //各门店有效订单量
    $.post(req_url,{orderid: order_id} ,function (data, status) {
        console.log(JSON.stringify(data));

        jyd_loading_toast_hide();

        if(status==500){
            jyd_toast({content: "服务器异常！"});
        }else{
            if(data.result == "success"){
                jyd_toast({content: "操作成功！"});

                if(action_name == "index"){
                    $("#"+order_id).find(".order_item_header .order_status .title").html("已完成");
                    $("#"+order_id).find(".order_item_footer .order_op .order_confirm").hide();
                    $("#"+order_id).find(".order_item_footer .order_op .order_cancel").hide();
                }else{
                    $("#order_show_container #order_base_info .order_status").html("已完成");
                    $("#order_show_op_footer #order_cancel").hide();
                    $("#order_show_op_footer #order_confirm").hide();
                }

            }else{
                jyd_toast({content: "操作成功！"});
            }
        }

    });
}

//取消订单
function order_cancel(order_id){

    jyd_loading_toast({'content':'加载中……'});
    //设置购物车数据
    var req_url = "/elephant_services/post_data?service_path=v1,order,cancel_order";
    //各门店有效订单量
    $.post(req_url,{orderid: order_id} ,function (data, status) {
        console.log(JSON.stringify(data));
        jyd_loading_toast_hide();
        if(status == 500){
            jyd_toast({content: "服务器异常！"});
        }else{
            if(data.result == "success"){
                jyd_toast({content: "操作成功！"});

                if(action_name == "index"){
                    $("#"+order_id).find(".order_item_header .order_status .title").html("已取消");
                    $("#"+order_id).find(".order_item_footer .order_op .order_confirm").hide();
                    $("#"+order_id).find(".order_item_footer .order_op .order_cancel").hide();
                }else{
                    $("#order_show_container #order_base_info .order_status").html("已取消");
                    $("#order_show_op_footer #order_cancel").hide();
                    $("#order_show_op_footer #order_confirm").hide();
                }
            }else{
                jyd_toast({content: "操作成功！"})
            }
        }
    });
}


//再次购买
function buy_again(){

    jyd_loading_toast({'content':'处理中……'});
    var product_list = product_id+":"+1;
    location.href = "/order/new?product_list="+product_list;
}